<?php
namespace App\Admin\Socialite;

use GuzzleHttp\RequestOptions;
use Laravel\Socialite\Two\User;
use Laravel\Socialite\Two\AbstractProvider;
use Illuminate\Support\Arr;


class DingtalkProvider extends AbstractProvider
{
    // 默认scopes
    protected $scopes = ['openid', 'profile'];


    // 钉钉没有这个玩意 https://open.dingtalk.com/document/orgapp/sso-overview
    protected function getAuthUrl($state){
    	return $this->buildAuthUrlFromBase('https://ssssssssssssssssssrefre.authing.cn/oidc/auth', $state);
    }

    // https://open.dingtalk.com/document/orgapp/obtain-the-access_token-of-an-internal-app?spm=ding_open_doc.document.0.0.454d2f16ZqujGZ
    protected function getTokenUrl(){
        return 'https://oapi.dingtalk.com/topapi/v1.0/oauth2/accessToken';
    }

    // https://open.dingtalk.com/document/orgapp/obtain-the-userid-of-a-user-by-using-the-log-free
    protected function getUserByToken($token){
        $userUrl = 'https://oapi.dingtalk.com/topapi/v2/user/getuserinfo?access_token='.$token;

        $response = $this->getHttpClient()->get($userUrl, [
            RequestOptions::FORM_PARAMS => [
                'code' => 'Bearer ',
            ],
        ]);

        $user = json_decode($response->getBody(), true);

        return $user;
    }

    /**
     *  subject 的缩写，唯一标识，一般为用户 ID
     */
    protected function mapUserToObject(array $user){
        return (new User)->setRaw($user)->map([
            'id'       => $user['sub'],
            'nickname' => Arr::get($user, 'name'),
            'name'     => Arr::get($user, 'name'),
            'email'    => Arr::get($user, 'userid'),
            'avatar'   => Arr::get($user, 'picture'),
        ]);
    }
}